package com.bee.beeAuth.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.bee.beeAuth.entity.SysMenu;
import com.bee.beeAuth.entity.out.MenuTree;
import com.bee.beeAuth.mapper.SysMenuMapper;
import com.bee.beeAuth.service.SysMenuService;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * <p>
 * 菜单表 服务实现类
 * </p>
 *
 * @author 陈国松
 * @since 2022-10-27
 */
@Service
public class SysMenuServiceImpl extends ServiceImpl<SysMenuMapper, SysMenu> implements SysMenuService {

    @Resource
    SysMenuMapper sysMenuMapper;

    @Override
    public List<MenuTree> selectMenuTreeByUserId(String userId) {
        //查到用户拥有的所有菜单
        List<SysMenu> sysMenus = sysMenuMapper.selectListByUserId(userId);
        List<MenuTree> ResultTree = new ArrayList<MenuTree>();

        //找到没有上级菜单的菜单
        List<SysMenu> RootMenus = sysMenus.stream().filter(sysMenu -> sysMenu.getParentId() == null)
                .collect(Collectors.toList());
        for (SysMenu rootMenu : RootMenus) {
            //构建成菜单树的结构
            MenuTree menuTree = new MenuTree();
            BeanUtils.copyProperties(rootMenu, menuTree);
            ResultTree.add(menuTree);
        }
        getChildren(sysMenus, ResultTree);
        return ResultTree;
    }

    /**
     * 递归构建菜单树
     * @param SysMenus
     * @param MenuTrees
     */
    public void getChildren(List<SysMenu> SysMenus,List<MenuTree> MenuTrees){
        //遍历根节点
        for (MenuTree menuTree : MenuTrees) {
            List<SysMenu> Childrens = SysMenus.stream().filter(sysMenu ->
                    (sysMenu.getParentId()!=null&&sysMenu.getParentId().equals(menuTree.getId())))
                    .collect(Collectors.toList());
            if(Childrens.size()!=0){
                List<MenuTree> TmpMenuTreeList = new ArrayList<MenuTree>();
                for (SysMenu children : Childrens) {
                    MenuTree TmpmenuTree = new MenuTree();
                    BeanUtils.copyProperties(children, TmpmenuTree);
                    TmpMenuTreeList.add(TmpmenuTree);
                }
                menuTree.setChildren(TmpMenuTreeList);
                getChildren(SysMenus,TmpMenuTreeList);
            }
        }
    }
}
